package me.zhangsanfeng.gpss.service.impl;

import me.zhangsanfeng.gpss.common.entity.Sorter;
import me.zhangsanfeng.gpss.common.utils.QueryConditionUtil;
import me.zhangsanfeng.gpss.common.utils.UpdateUtil;
import me.zhangsanfeng.gpss.dao.ProductRepository;
import me.zhangsanfeng.gpss.entity.Product;
import me.zhangsanfeng.gpss.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductRepository repository;

    @Override
    public Product insert(Product product) {
        return repository.save(product);
    }

    @Override
    public List<Product> insertBatch(List<Product> products) {
        return repository.saveAll(products);
    }

    @Override
    public void delete(Product product) {
        repository.delete(product);
    }

    @Override
    public void deleteBatch(List<Product> products) {
        repository.deleteAll(products);
    }

    @Override
    public Product update(Product product) {
        UpdateUtil.copyNullProperties(repository.getOne(product.getId()),product);
        return repository.saveAndFlush(product);
    }

    @Override
    public List<Product> updateBatch(List<Product> products) {
        for (Product product : products) {
            UpdateUtil.copyNullProperties(repository.getOne(product.getId()),product);
        }
        return repository.saveAll(products);
    }

    @Override
    public Product selectOne(Product product) {
        return repository.findOne(Example.of(product)).get();
    }

    @Override
    public List<Product> selectList(Product product) {
        /*排序标识*/
        Sorter sorter = product.getSorter();

        Map<String, Object> condition;
        //不排序
        if (null == sorter.getDesc() && null == sorter.getAsc() && null == sorter.getPrior()) {
            condition = QueryConditionUtil.getWhereCondition(product, false, false);
        } else {
            condition = QueryConditionUtil.getWhereCondition(product, false, true);
        }

        return QueryConditionUtil.getQueryInstanceOfList(condition, repository);
    }

    @Override
    public Page<Product> selectPage(Product product) {
        /*排序标识*/
        Sorter sorter = product.getSorter();

        Map<String, Object> condition;
        if (null == sorter.getDesc() && null == sorter.getAsc() && null == sorter.getPrior()){
            condition = QueryConditionUtil.getWhereCondition(product, true, false);
        }else {
            condition = QueryConditionUtil.getWhereCondition(product, true, true);
        }

        return QueryConditionUtil.getQueryInstanceOfPage(condition,repository);
    }
}
